package cn.slipi.pan.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.slipi.pan.common.base.BaseController;
import cn.slipi.pan.common.response.ApiResult;
import cn.slipi.pan.web.controller.req.SearchListReq;
import cn.slipi.pan.web.controller.res.ResourceItem;
import cn.slipi.pan.web.controller.res.SearchListRes;
import cn.slipi.pan.web.entity.AuthEntity;
import cn.slipi.pan.web.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Controller
@Mapping("/search")
public class SearchController extends BaseController {

    public static final String HOST_HEADER = "Host";
    public static final String REFERER_HEADER = "Referer";
    public static final String AUTHORIZATION_HEADER = "X-Authorization";

    @Inject
    private AuthService authService;

    @Post
    @Mapping("/list")
    public ApiResult<?> list(Context ctx, @Body SearchListReq searchListReq) {
        String license = ctx.header("license");
        if (StringUtils.isBlank(license)) {
            return fail("license error");
        }
        AuthEntity authEntity = authService.getAuthByLicense(license);
        if (authEntity == null) {
            return fail("license error");
        } else {
            String url = "https://fc-resource-node-api.krzb.net/api/v1/pan/search?";
            url = url + "t=" + System.currentTimeMillis();
            url = url + "&version=v2&line=0&site=dalipan";
            url = url + "&kw=" + URLEncoder.encode(searchListReq.getKeyword(), StandardCharsets.UTF_8);
            if (StrUtil.isNotBlank(searchListReq.getFileType())) {
                url = url + "&category=" + searchListReq.getFileType();
            }
            if (StrUtil.isNotBlank(searchListReq.getDateRange())) {
                url = url + "&diffDay=" + searchListReq.getDateRange();
            }
            if (StrUtil.isNotBlank(searchListReq.getSearchType())) {
                url = url + "&searchType=" + searchListReq.getSearchType();
            }
            if (StrUtil.isNotBlank(searchListReq.getSourceType())) {
                url = url + "&resType=" + searchListReq.getSourceType();
            }
            if (StrUtil.isNotBlank(searchListReq.getMinSize())) {
                url = url + "&minSize=" + searchListReq.getMinSize();
            }
            if (StrUtil.isNotBlank(searchListReq.getMaxSize())) {
                url = url + "&maxSize=" + searchListReq.getMaxSize();
            }
            url = url + "&page=" + searchListReq.getPage();

            // 创建HttpRequest对象，并配置URL
            HttpRequest request = HttpRequest.get(url);
            // 设置请求头，可以链式调用设置多个头信息
            request.header(AUTHORIZATION_HEADER, authEntity.getToken());
            request.header(HOST_HEADER, "fc-resource-node-api.krzb.net");
            request.header(REFERER_HEADER, "https://www.dashengpan.com/");
            request.timeout(20000);
            HttpResponse response = request.execute();
            if (response == null) {
                return fail("未检索到相关数据");
            }
            if (!response.isOk()) {
                return fail("未检索到相关数据");
            }
            String responseBody = response.body();
//            String response = HttpUtil.get(url, 20000);
            if (StrUtil.isNotBlank(responseBody)) {
                JSONObject responseJsonObj = JSONUtil.parseObj(responseBody);
                Integer total = responseJsonObj.getInt("total");
                //计算总页码 const pageCountReal = Math.min(Math.ceil(total / 15), 666);
                Integer totalPage = (int) Math.min(Math.ceil((double) total / 15), 666);
                //获取列表数据
                List<ResourceItem> list = new ArrayList<>();
                JSONArray resources = responseJsonObj.getJSONArray("resources");
                resources.forEach(item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    JSONObject resourceItemObj = jsonObject.getJSONObject("res");
                    if (resourceItemObj != null) {
                        ResourceItem resourceItem = new ResourceItem();
                        resourceItem.setId(resourceItemObj.getStr("id"));
                        resourceItem.setType(resourceItemObj.getStr("type"));
                        resourceItem.setFilename(resourceItemObj.getStr("filename"));
                        resourceItem.setSize(resourceItemObj.getStr("size"));
                        resourceItem.setParent(resourceItemObj.getStr("parent"));
                        resourceItem.setUpdateTime(resourceItemObj.getStr("updatetime"));
                        list.add(resourceItem);
                    }
                });

                SearchListRes searchListRes = new SearchListRes();
                searchListRes.setList(list);
                searchListRes.setTotalPage(totalPage);

                return success(searchListRes);
            }
            return fail("未检索到相关数据");
        }
    }


    @Get
    @Mapping("/detail")
    public ApiResult<?> detail(Context ctx, @Param("id") String id, @Param("type") String type, @Param("parent") String parent) {
        String license = ctx.header("license");
        if (StringUtils.isBlank(license)) {
            return fail("license error");
        }
        AuthEntity authEntity = authService.getAuthByLicense(license);
        if (authEntity == null) {
            return fail("license error");
        } else {
            String url = "https://fc-resource-node-api.krzb.net/api/v1/pan/detail?";
            //"t=" + Date.now() + "&version=v2" + "&id=" + id + "&size=15&type=" + type + "&parent=" + parent;
            url = url + "t=" + System.currentTimeMillis();
            url = url + "&version=v2&size=15";
            url = url + "&id=" + id;
            url = url + "&type=" + type;
            url = url + "&parent=" + parent;
            // 创建HttpRequest对象，并配置URL
            HttpRequest request = HttpRequest.get(url);
            // 设置请求头，可以链式调用设置多个头信息
            request.header(AUTHORIZATION_HEADER, authEntity.getToken());
            request.header(HOST_HEADER, "fc-resource-node-api.krzb.net");
            request.header(REFERER_HEADER, "https://www.dashengpan.com/");
            request.timeout(20000);
            HttpResponse response = request.execute();
            if (response == null) {
                return fail("未检索到相关数据");
            }
            if (!response.isOk()) {
                return fail("未检索到相关数据");
            }
            String responseBody = response.body();
            if (StrUtil.isNotBlank(responseBody)) {
                JSONObject responseJsonObj = JSONUtil.parseObj(responseBody);


                String url1 = "https://fc-resource-node-api.krzb.net/api/v1/pan/url?";
                //"t=" + Date.now() + "&version=v2" + "&id=" + id;
                url1 = url1 + "t=" + System.currentTimeMillis();
                url1 = url1 + "&version=v2";
                url1 = url1 + "&id=" + id;
                // 创建HttpRequest对象，并配置URL
                HttpRequest request1 = HttpRequest.get(url1);
                // 设置请求头，可以链式调用设置多个头信息
                request1.header(AUTHORIZATION_HEADER, authEntity.getToken());
                request1.header(HOST_HEADER, "fc-resource-node-api.krzb.net");
                request1.header(REFERER_HEADER, "https://www.dashengpan.com/");
                request1.timeout(20000);
                HttpResponse response1 = request1.execute();
                if (response1 == null) {
                    return fail("未检索到相关数据");
                }
                if (!response1.isOk()) {
                    return fail("未检索到相关数据");
                }
                String responseBody1 = response1.body();
                if (StrUtil.isNotBlank(responseBody1)) {
                    JSONObject responseJsonObj1 = JSONUtil.parseObj(responseBody1);
                    if (responseJsonObj.getBool("haspwd")) {
                        String panUrl = responseJsonObj1.getStr("data") + "?pwd=" + responseJsonObj.getStr("pwd");
                        return success("success", panUrl);
                    } else {
                        String panUrl = responseJsonObj1.getStr("data");
                        return success("success", panUrl);
                    }
                }
                return fail("未检索到相关数据");
            }
            return fail("未检索到相关数据");
        }
    }

}
